package com.sxhuayuan.parking.job;

import com.sxhuayuan.parking.service.OrderService;
import com.sxhuayuan.parking.utils.DateUtils;
import com.sxhuayuan.parking.utils.SettingUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * 订单超时取消任务
 * 
 * @author DELL
 *
 */
@Component
@Lazy(false)
public class OrderTimeoutJob {

	Logger log = LoggerFactory.getLogger(getClass());

	@Autowired
	OrderService orderService;

	@Scheduled(cron = "0 59 23 * * ?")
	public void clearTimoutOrders() {
		try {
			log.debug("删除过期订单...");
			Integer orderTimeoutDays = SettingUtils.get().getOrderTimeoutDays();
			if (orderTimeoutDays == null || orderTimeoutDays <= 1) {
				log.error("订单超时时间错误，必须大于1");// 最少保留1天的订单
				return;
			}
			// 获取指定天数前的那一天的最后一刻，如3天前的晚上23:59:59
			Date date = DateUtils.getEndTimeOfOneday(-orderTimeoutDays);
			String endtime = DateUtils.format(date);
			log.debug("删除{}之前的未支付订单: {}", endtime);
			orderService.clearTimeoutOrders(endtime);
		} catch (Exception e) {
			log.error("", e);
		}
	}

	public static void main(String[] args) {
		System.out.println(DateUtils.format(DateUtils.getEndTimeOfOneday(-3)));
	}
}
